package com.example.prison.config;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.example.prison.entity.*;
import com.example.prison.service.*;
import com.example.prison.util.AttDeviceUtil;
import com.example.prison.util.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/iclock")
/**
 * 1.初始化
 * 2.注册
 * 3.push
 * 4.心跳
 * 5.心跳处理结果
 * 6.实时记录
 */
public class AccPushProccesor {


    private static boolean test = true;
    private static int index = 0;

    private static List<String> cmds = null;
    static {
        cmds = GenerateCmd.cmd();
    }

    public static String time = "9999-12-31 11:59:59";
    public static String number;

    public static Map<String,String> heatMap = new HashMap<>();

    @Autowired
    private PeopleManageService peopleManageService;
    @Autowired
    private VisitorAppointmentService visitorAppointmentService;
    @Autowired
    private AttendanceDeviceInfoService attendanceDeviceInfoService;
    @Autowired
    private AttendanceListService attendanceListService;
    @Autowired
    private LeaveManagementService leaveManagementService;
    @Autowired
    private SecurityListService securityListService;
    @Autowired
    private SecurityDeviceInfoService securityDeviceInfoService;
    @Autowired
    private DeviceManagementService deviceManagementService;

    /**
     * 处理初始化请求的
     * @return
     */
    @RequestMapping(value = "/cdata",method = RequestMethod.GET)
    public String init(String SN, String pushver, String options, HttpServletRequest req){
//        System.out.println("#######请求的URL:"+req.getServletPath());
        Map<String,String> param = convertMap(req);
//        System.out.println("######请求的参数"+param.toString());
//        System.out.println("######请求完整URL:"+req.getServletPath()+"?"+param.toString().trim().replace(", ", "&").replace("{", "").replace("}", ""));
        System.out.println("SN..."+SN+"...pushver..."+pushver+"...options..."+options+"..."+new SimpleDateFormat("HH:mm:ss").format(new Date()));

        return "OK\n"+"PushProtVer=3.1.2";

    }

    /**
     * 处理注册请求的
     * @return
     */
    @RequestMapping("/registry")
    public String registry(@RequestBody String deviceData, HttpServletRequest req, String SN){

//        System.out.println("#######请求的URL:"+req.getServletPath());
        Map<String,String> param = convertMap(req);
//        System.out.println("######请求的参数"+param.toString());
//        System.out.println("######请求完整URL:"+req.getServletPath()+"?"+param.toString().trim().replace(", ", "&").replace("{", "").replace("}", ""));
        System.out.println(deviceData);

        return "RegistryCode=Uy47fxftP3";
    }

    /**
     * 处理push请求
     *
     * @return
     */
    @RequestMapping(value = "/push")
    public String push(HttpServletRequest req){
        System.out.println("进入到push请求.....");
//        System.out.println("#######请求的URL:"+req.getServletPath());
        Map<String,String> param = convertMap(req);
//        System.out.println("######请求的参数"+param.toString());
//        System.out.println("######请求完整URL:"+req.getServletPath()+"?"+param.toString().trim().replace(", ", "&").replace("{", "").replace("}", ""));
        StringBuffer sb = new StringBuffer();
        sb.append("ServerVersion=3.0.1\n");
        sb.append("ServerName=ADMS\n");
        sb.append("PushVersion=3.0.1\n");
        sb.append("ErrorDelay=30\n");
        sb.append("RequestDelay=2\n");
        sb.append("TransTimes=00:0014:00\n");
        sb.append("TransInterval=1\n");
        sb.append("TransTables=User Transaction\n");
        sb.append("Realtime=1\n");
        sb.append("SessionID=30BFB04B2C8AECC72C01C03BFD549D15\n");
        sb.append("TimeoutSec=10\n");

        return sb.toString();
    }

    /*
     * 处理心跳请求
     *
     */
    @RequestMapping("/getrequest")
    public String heartbeat(String SN){



//        System.out.println("#######请求的URL:"+req.getServletPath());
        //     Map<String,String> param = convertMap(req);
//        System.out.println("######请求的参数"+param.toString());
//        System.out.println("######请求完整URL:"+req.getServletPath()+"?"+param.toString().trim().replace(", ", "&").replace("{", "").replace("}", ""));
        System.out.println("进入到心跳请求...."+SN+new Date());

        //判断设备在线
        if(ObjectUtils.isNotEmpty(attendanceDeviceInfoService.getOneByNumber(SN))) {
            AttendanceDeviceInfo device = attendanceDeviceInfoService.getOneByNumber(SN);
            device.setDeviceStatus("在线");
            attendanceDeviceInfoService.update(device, device.getDeviceId());
        }
        if(ObjectUtils.isNotEmpty(securityDeviceInfoService.getOneByNumber(SN))) {
            SecurityDeviceInfo device = securityDeviceInfoService.getOneByNumber(SN);
            device.setDeviceStatus("在线");
            securityDeviceInfoService.update(device, device.getDeviceId());
        }
        number = SN;
        time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        String heartTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());

        heatMap.put(SN,heartTime);

//        time = "2023-07-26 14:50:00";
//        number = "CPON221560008";

        //cmd.txt 放在d盘
        BufferedReader br = null;
        File file = new File("d://cmd.txt");//elegent

        StringBuffer sb = new StringBuffer();

        if(file.exists()){
            try {
                br = new BufferedReader(new FileReader(file));
                String cmd = "";
                while((cmd = br.readLine())!=null){
                    if(cmd.startsWith("C")){
                        //正常的命令
                        sb.append(cmd+"\r\n\r\n");
                        //return sb.toString();
                    }else if(cmd.startsWith("D")){
                    }else{
                        //进到这里目前看只能是E开头，则表示人员头像
                    }
                }
                br.close();
                file.delete();
                Thread.sleep(1000);
                return sb.toString();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }else if(test){
            //test = false;
            if(index < cmds.size()){
                System.out.println("命令为...."+cmds.get(index));
                return cmds.get(index++);
            }else{
                test = false;
            }
            // return GenerateCmd.cmd();
            return "OK";
        }else{
            return "OK";
        }
        return "OK";


       /* if(userPic.length()>0){
            try {
                InputStream is = new FileInputStream(new File("d://lz.jpg"));//从磁盘读取照片
                int length = is.available();
                byte[] buffer = new byte[length];
                is.read(buffer);
                String base64 =  Base64.getEncoder().encodeToString(buffer);
                userPic = userPic+"\tsize="+base64.length()+"\tcontent="+base64+"\r\n\r\n";
            } catch (IOException e) {
                e.printStackTrace();
            }
            String cmd =userCmd;
            userPic = "";
            return cmd;
        }else{
            return "OK";
        }*/
    }

    public Map<String, String> convertMap(HttpServletRequest request) {
        Map<String, String> returnMap = new HashMap<>();
        // 转换为Entry
        Set<Map.Entry<String, String[]>> entries = request.getParameterMap().entrySet();
        for (Map.Entry<String, String[]> entry : entries) {
            String key = entry.getKey();
            StringBuffer value = new StringBuffer("");
            String[] val = entry.getValue();
            if (null != val && val.length > 0) {
                for (String v:val) {
                    value.append(v);
                }
            }
            returnMap.put(key, value.toString());
        }
        return returnMap;
    }

    @RequestMapping("/ping")
    public String ping(HttpServletRequest req){
        System.out.println("设备上传时通过Ping请求维持心跳");
        System.out.println("#######请求的URL:"+req.getServletPath());
//        Map<String,String> param = convertMap(req);
//        System.out.println("######请求的参数"+param.toString());
//        System.out.println("######请求完整URL:"+req.getServletPath()+"?"+param.toString().trim().replace(", ", "&").replace("{", "").replace("}", ""));
        return "OK";
    }

    public static String anFangGetTime(String data) {
        String date = data.substring(data.indexOf("time=") + 5, data.indexOf("time=") + 24).trim();
        return date;
    }

    public static String anFangGetPin(String data) {
        String pin = data.substring(data.indexOf("pin=") + 4, data.indexOf("pin=") + 5).trim();
        return pin;
    }

    public static String kaoQinGetPeople(String data) {
        String[] dataArray = data.replaceAll("\\s+", ",").split(",");
        return dataArray[0];
    }

    public static String kaoQinGetTime(String data) {
        String[] dataArray = data.replaceAll("\\s+", ",").split(",");
        return dataArray[1] + " " + dataArray[2];
    }

    @RequestMapping(value = "/cdata",method = RequestMethod.POST)
    public String handleForm(@RequestBody String data,String SN,HttpServletRequest  req,String table,String AuthType){

        String time = ""; String pin = "";String id = "";

        System.out.println("上传的表名为：....。。。。。。。。"+table);
        if(table.equals("rtlog")) { //安防
            time = anFangGetTime(data); pin = anFangGetPin(data);
            //添加安防记录
            SecurityList securityList = new SecurityList();
            securityList.setRecordId(0);
            securityList.setPin(pin);
            securityList.setTime(time);
            securityList.setSn(SN);
//            securityList.setAddress(securityDeviceInfoService.getOneByNumber(SN).getDeviceArea());
            securityListService.addSecurityRecord(securityList);
            System.out.println("time:"+time+"\tpin:"+pin);
        } else if(table.equals("ATTLOG")) { //考勤
            time = kaoQinGetTime(data); id = kaoQinGetPeople(data);
            //添加考勤记录
            AttendanceList attendanceList = new AttendanceList();
            attendanceList.setRecordId(0);
            attendanceList.setId(id);
            attendanceList.setTime(time);
            attendanceList.setSn(SN);
            if(ObjectUtils.isNotEmpty(attendanceDeviceInfoService.getOneByNumber(SN))) {
                attendanceList.setAccess(attendanceDeviceInfoService.getOneByNumber(SN).getAccess());
            }
            if(ObjectUtils.isEmpty(peopleManageService.getOneListByName(id))) {
                //id.startsWith("P")
                attendanceList.setPtype("访客");
            } else {
                attendanceList.setPtype("内部人员");
            }
            attendanceListService.addAttendanceRecord(attendanceList);
            if(ObjectUtils.isNotEmpty(leaveManagementService.getLeavesByNameAndStatus(id,"未销假"))) {
                //若人员为请假人员，则销假
                List<LeaveManagement> leaves = leaveManagementService.getLeavesByNameAndStatus(id,"未销假");
                for (LeaveManagement leave : leaves) {
                    leave.setStatus("已销假");
                    leaveManagementService.endLeave(leave);
                }
            }

            //门岗检查、隔离仓(设备)、值班警察人员绑定  PID暂时定为手机号
//            String res = AttDeviceUtil.bingPeople(SN, id, time, attendanceList);
            String beginTime = time;
            String endTime = TimeUtil.minReduce(time,10);
            if(attendanceList.getPtype() == "访客" ) {
                if (ObjectUtils.isNotEmpty(visitorAppointmentService.getByPIDAndTime(id, time.substring(0, 10)))) {
                    //此次考勤的访客数据
                    VisitorAppointment visitor = visitorAppointmentService.getByPIDAndTime(id, time.substring(0, 10));
                    if (ObjectUtils.isNotEmpty(attendanceListService.getBySNOrderByTime(SN, beginTime, endTime).getList().get(1))) {
                        //获取上一条10分钟之内的带领人的记录
                        AttendanceList latestAttend = attendanceListService.getBySNAndTimeAndPType(SN, beginTime, endTime, "内部人员");
                        //AttendanceList latestAttend = attendanceListService.getBySNOrderByTime(SN, beginTime, endTime).getList().get(1);
                        if (ObjectUtils.isNotEmpty(peopleManageService.getByPID(latestAttend.getId()))) {
                            //获取对应带领人信息
                            PeopleManage people = peopleManageService.getByPID(latestAttend.getId());
                            if (visitor.getVisitorStatus() == "0" && ObjectUtils.isEmpty(visitor.getReceptionist())) {
                                //绑定带路人，修改访客状态为已入场  0未进场/1已入场/2已通过监狱门岗检查/3已通过隔离仓检查/4已通过值班人员检查/5已出场
                                visitor.setVisitorStatus("1");
                                if(attendanceList.getAccess().contains("出")) {
                                    visitor.setOutReceptionist(people.getName());
                                } else {
                                    visitor.setReceptionist(people.getName());
                                }
                            }
                        }
                    }
                    visitorAppointmentService.update(visitor, visitor.getId());
                }
            }
            else {
                if (ObjectUtils.isNotEmpty(peopleManageService.getByPID(id))) {
                    //此次考勤的人员数据
                    PeopleManage people = peopleManageService.getByPID(id);
                    if (ObjectUtils.isNotEmpty(attendanceListService.getBySNOrderByTime(SN, beginTime, endTime).getList().get(2))) {
                        //获取上一条10分钟之内的访客记录
                        AttendanceList latestAttend = attendanceListService.getBySNAndTimeAndPType(SN, beginTime, endTime, "访客");
                        //AttendanceList latestAttend = attendanceListService.getBySNOrderByTime(SN, beginTime, endTime).getList().get(2);
                        if ( ObjectUtils.isNotEmpty(visitorAppointmentService.getByPIDAndTime(latestAttend.getId(), time.substring(0, 10))) ) {
                            //获取对应访客人信息
                            VisitorAppointment visitor = visitorAppointmentService.getByPIDAndTime(latestAttend.getId(), time.substring(0, 10));
                            if ( visitor.getVisitorStatus() == "1" && (people.getPost().contains("哨")||people.getPost().contains("门")) ) {
                                //绑定监狱门岗人员，修改访客状态为2已通过监狱门岗检查  0未进场/1已入场/2已通过监狱门岗检查/3已通过隔离仓检查/4已通过值班人员检查/5已出场
                                visitor.setVisitorStatus("2");
                                if(attendanceList.getAccess().contains("出")) {
                                    visitor.setOutGateSentry(people.getName());
                                } else {
                                    visitor.setInGateSentry(people.getName());
                                }
                                //visitor.setInGateSentry(people.getName());
                            } else if ( visitor.getVisitorStatus() == "3" && people.getPost().contains("值班") ) {
                                //绑定值班人员，修改访客状态为4已通过值班人员检查  0未进场/1已入场/2已通过监狱门岗检查/3已通过隔离仓检查/4已通过值班人员检查/5已出场
                                visitor.setVisitorStatus("4");
                                if(attendanceList.getAccess().contains("出")) {
                                    visitor.setOutDutyPolice(people.getName());
                                } else {
                                    visitor.setInDutyPolice(people.getName());
                                }
                                //visitor.setInDutyPolice(people.getName());
                            }
                            visitorAppointmentService.update(visitor, visitor.getId());
                        }
                    }
                }
            }

            System.out.println("time:"+time+"\tid:"+id);
        }
        System.out.println("设备上传的实时记录为..."+data+"序列号。。。。。。。"+SN);

        String verification = "AUTH=SUCCESS\r\n";
        String cmd = "CONTROL DEVICE 1 1 1 5\r\n\r\n";
        //若上传的实时记录类型为biophoto 若需要解析base64的比对照片 请参照ConvertBase642Img 类中的方法。
//        System.out.println("#######请求设备上传的实时记录为的URL:"+req.getServletPath());
        Map<String,String> param = convertMap(req);
        StringBuffer sb = new StringBuffer();
//        System.out.println("######请求的参数"+param.toString());
//        System.out.println("######请求完整URL:"+req.getServletPath()+"?"+param.toString().trim().replace(", ", "&").replace("{", "").replace("}", ""));
        if (("device").equals(AuthType)){

            // return verification+"\r\n"+data+"\r\n"+sb.append(heartbeat(SN));
            System.out.println("回复的数据是...\r\n"+verification+data+"\r\n"+cmd);
            return verification+data+"\r\n"+cmd;

        }else {

            return "OK";
        }


    }


    @RequestMapping(value = "/querydata",method = RequestMethod.POST)
    public String query(@RequestBody String querrydata,HttpServletRequest req){
        String[] dataArray = querrydata.split("\r\n");

        int count = dataArray.length;
        String tableName = dataArray[0].split(" ")[0];
        System.out.println("查询信息是。。。。。"+querrydata);
        String returnValue = tableName+"="+count;
        // System.out.println(returnValue);
        // System.out.println("#######请求设备上传的实时记录为的URL:"+req.getServletPath());
        Map<String,String> param = convertMap(req);
        StringBuffer sb = new StringBuffer();
        // System.out.println("######请求的参数"+param.toString());
        // System.out.println("######请求完整URL:"+req.getServletPath()+"?"+param.toString().trim().replace(", ", "&").replace("{", "").replace("}", ""));

        return returnValue;

    }
    @RequestMapping(value = "/rtdata",method = RequestMethod.GET)
    public String rtdata(String type){
        //  System.out.println(type+"11111111111");
        System.out.println("11111111111");
        //String time = new DateUtils().Time();

        // String ServerTZ = "ServerTZ=+0100";
        System.out.println("11111111111");
        return "DateTime=716116020"+","+"ServerTZ=+0800";//格林威治时间减去八小时return

    }


    @RequestMapping(value="/devicecmd")
    public String deviceCmd(@RequestBody String cmdResult,HttpServletRequest req){
        System.out.println("命令返回的结果为..."+cmdResult);
//        System.out.println("#######请求的URL:"+req.getServletPath());
        Map<String,String> param = convertMap(req);
//        System.out.println("######请求的参数"+param.toString());
//        System.out.println("######请求完整URL:"+req.getServletPath()+"?"+param.toString().trim().replace(", ", "&").replace("{", "").replace("}", ""));
        return "OK";
    }
    @RequestMapping(value = "/file")
    public  String File(@RequestBody String SN,String cmdid,String fileseq,String contenttype,String count){


        return "OK";
    }

}
